//
//  HDNetwork.swift
//  Excited
//
//  Created by X140Yu on 6/14/16.
//  Copyright © 2016 X140Yu. All rights reserved.
//
import Alamofire
import Foundation
import PKHUD


/**
 HD request, always .POST
 - parameter url:        "login" || "credit/123"
 - parameter parameters: ["uid": "123123123", "pwd": "asjdk"]
 - parameter completion:
 - parameter onError:
 */

/// functions for request VPS's data
class HDNetwork {
    
    static func hd_request(
        url: String,
        parameters: [String: AnyObject],
        completion: (objs: NSArray) -> Void,
        onError: (message: String) -> Void
        ) {
        Alamofire.request(.GET, baseURL + url, parameters: parameters).responseJSON { (result) in
            // debug 输出
            debugPrint(baseURL + url)
            for pm in parameters {
                debugPrint(pm.0 + " : " + (pm.1 as! String))
            }
            
            if let value = result.result.value as? [String: AnyObject] {
                if let errorCode = value["code"] as? Int {
                    let error = HDError(code: errorCode)
                    switch error {
                    case .Success:
                        let array = value["result"] as! NSArray
                        completion(objs: array)
                    default:
                        onError(message: error.rawValue)
                    }
                    return
                }
            }
            onError(message: HDError.DefaultError.rawValue)
        }
    }
    
    /*
     * 新闻列表
     */
    static func fetchNewsListWith(index: Int, completion: (newsList: [HDNewsListItem]) -> Void, onError: (message: String) -> Void) {
        hd_request("newslist", parameters: ["page": "\(index)"], completion: { (objs) in
            guard let newsArray = NSArray.modelArrayWithClass(HDNewsListItem.self, json: objs) as? [HDNewsListItem] else { onError(message: "解析错误"); return }
            completion(newsList: newsArray)
        }) { (message) in
            onError(message: message)
        }
    }
    
    /*
     *单个新闻详情
     */
    static func fetchNewsItemWith(nid: String, completion: (news: HDNews) -> Void, onError: (message: String) -> Void) {
        hd_request("newsdetail", parameters: ["nid": nid], completion: { (objs) in
            guard let res = objs[0] as? [String: AnyObject] else { onError(message: "解析错误"); return }
            guard let news = HDNews.modelWithJSON(res) else { onError(message: "解析错误"); return }
            completion(news: news)
        }) { (message) in
            onError(message: message)
        }
    }
}